<template>
  <div class="mask">
    <!-- vue animation -->
    <transition name="fade">
      <!-- mask outter -->
      <div class="mask-cover" v-if="isShowMask" @click.stop="closeByClickMask">
        <!-- mask content -->
        <div class="mask-content" v-if="isShowMask">
          <!-- slot -->
          <slot name="default"></slot>
        </div>
      </div>
    </transition>
  </div>
</template>

<script>
export default {
  name: "DMask",
  props: {
    // is show the mask
    isShowMask: {
      type: Boolean,
      default: false,
    },
    // can close the mask by click itself
    canCloseByClickMask: {
      type: Boolean,
      default: true,
    },
  },
  watch: {
    isShowMask(newVal) {
      newVal ? this.stopScroll() : this.startScroll();
    },
  },
  methods: {
    // show the mask
    showMask() {
      this.$emit("handleShowMask");
    },
    // close the mask
    closeMask() {
      this.$emit("handleCloseMask");
    },
    // close the mask by click itself
    closeByClickMask(e) {
      if (this.canCloseByClickMask && e.target.className === "mask-cover") {
        this.$emit("handleCloseMask");
      }
    },
    // prevent default touchmove scroll event
    bodyScroll(event) {
      event.preventDefault();
    },
    // add stop scroll event
    stopScroll() {
      document.body.style.overflow = "hidden";
      document.addEventListener("touchmove", this.bodyScroll, false);
    },
    // remove stop scroll event
    startScroll() {
      document.body.style.overflow = "";
      document.removeEventListener("touchmove", this.bodyScroll, false);
    },
  },
};
</script>

<style scoped lang="less">
.mask {
  position: relative;

  // mask outter
  .mask-cover {
    position: fixed;
    z-index: 9999;
    top: 0;
    left: 0;
    height: 100%;
    width: 100%;
    background: rgba(0, 0, 0, 0.5);
    // backdrop-filter: blur(20px);

    // mask content
    .mask-content {
      position: fixed;
      top: 23%;
      left: 50%;
      transform: translateX(-50%);
      z-index: 10000;
    }
  }
}

// vue animation
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s ease;
}

.fade-enter,
.fade-leave-to {
  opacity: 0;
}
</style>
